package com.lm.jcr;

import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.core.TransientRepository;
import org.junit.Test;

import javax.jcr.*;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 19:26 2024/6/6
 */
public class FisrtTest {
    public static void main(String[] args) throws RepositoryException {
        Repository repository = JcrUtils.getRepository();
        Session session = repository.login(new GuestCredentials());
        try {
            String user = session.getUserID();
            String name = repository.getDescriptor(Repository.REP_NAME_DESC);
            System.out.println(
                    "Logged in as " + user + " to a " + name + " repository.");
        } finally {
            session.logout();
        }
    }

    @Test
    public void test() throws RepositoryException {
        Repository repository = new TransientRepository();

        // 创建一个session
        Session session = repository.login(new SimpleCredentials("admin",
                "admin".toCharArray()));
        try {
            // 得到根节点(发现root变量，root，一般树结构的顶层节点叫做root)
            Node root = session.getRootNode();

            // 添加节点数据（仔细看hello节点和world节点的组织方式，可以发现它是一颗树形结构）
            Node hello = root.addNode("hello");
            Node world = hello.addNode("world");
            world.setProperty("message", "Hello, World!");

            // 保存数据
            session.save();

            // 数据查询
            Node node = root.getNode("hello/world");
            System.out.println(node.getPath());
            System.out.println(node.getProperty("message").getString());

            // 数据删除
            root.getNode("hello").remove();
            session.save();
        } finally {
            session.logout();
        }
    }
}
